const eventChennel=require('./eventChannel');
class ScanQRcode {
    QRcodeArray=[];

    create(key,value=''){
        this.QRcodeArray.push({key,value});
        this.overtime(key,60)
    }
    set(key,value){
        this.QRcodeArray.forEach(item=>{
            if(item.key==key){
                item.value=value;
                this.overtime(key,1)
            }
        })
    }
    get(key){
        let array=this.QRcodeArray.filter(item=>item.key==key)
        let userInfo=array[0]?.value;
        return userInfo;
    }
    overtime(key,time){
        let maxTime=time;
        // 二维码未扫码自动删除
        const timer=setInterval(() => {
            maxTime--;
            if(maxTime==0){
                clearInterval(timer);
                this.QRcodeArray=this.QRcodeArray.filter(item=>item.key!=key)
                // 触发所有连接websocket的页面
                eventChennel.io.sockets.emit('ScanCodeOvertime',key)
            }
        }, 1000);
        // 扫码后停止自动删除
        eventChennel.socket.on('deteleTimer',(res)=>{
            if(key==res){
                maxTime=60*3;
            }
        })
    }
}

module.exports = new ScanQRcode();